export default {
	namespaced:true,
	state:()=>({
		cartList:JSON.parse(uni.getStorageSync('cart')||'[]')
	}),
	mutations:{
		setaddShop(state,obj){//添加商品
		console.log(obj)
		let list=state.cartList
		const item=list.find(x=>x.goods_id==obj.goods_id)//flag假未定义,真返回对象
		!item?list.push(obj):item.goods_count+=obj.goods_count;
		this.commit('cart/setStorge')
		},
		setStorge(state){//持久化保存
			uni.setStorageSync('cart',JSON.stringify(state.cartList))
		},
		setitemnum(state,obj){// 商品数量的加减
			state.cartList.forEach(v=>{
				if(v.goods_id==obj.id){
					let num=v.goods_count+obj.num;
					if(num>0){
						v.goods_count+=obj.num;
					}
				}
			})
			this.commit('cart/setStorge')
		},
		setgoodsState(state,obj){//单选
			state.cartList.forEach(v=>{
				if(v.goods_id==obj.id){
					v.goods_state=!v.goods_state
				}
			})
			this.commit('cart/setStorge')
		},
		reovmitem(state,id){//删除商品
			let list=state.cartList;
			for(var i=0;i<list.length;i++){
				if(list[i].goods_id==id){
					list.splice(i,1)
					this.commit('cart/setStorge')
					break
				}
			}	
		},
		chenAllState(state,bool){// 全选
			state.cartList.forEach(v=>{
				v.goods_state=!bool;
			})
			this.commit('cart/setStorge')
		}
	},
	getters:{
		getshop(state){
			let num=0;//商品数量
			let TotalPrice=0;//总价
			let ckendAll=true;//全选
			let numTtrue=0;//选中的数量
			let list=state.cartList
			list.forEach(v=>{
				if(v.goods_state){
				TotalPrice+=v.goods_count*v.goods_price
				numTtrue+=v.goods_count;
				}
				num+=v.goods_count//数量
				if(!v.goods_state){
					 ckendAll=false;
				}
			});
			(list.length==0)&&(ckendAll=false)
			return {
				num,list,TotalPrice,ckendAll,numTtrue
			}
			this.commit('cart/setStorge')
		}
	}
}